import fs from 'fs'
import path from 'path'
import crypto from 'crypto'
/**
 * create folder 
 * @param {String} folderPath 
 */
export function mkdir(folderPath) {
  if (fs.existsSync(folderPath)) {
    return true;
  }  
  if (path.extname(folderPath) != '') {
    folderPath = path.dirname(folderPath);
  }
  fs.mkdirSync(folderPath, { recursive: true });
  return true;
}

export function existsFile(filePath) {
  return fs.existsSync(filePath);
}
export function isFile(filePath) {
  if (existsFile(filePath)) {
    let stat = fs.statSync(filePath);
    return stat.isFile();  
  }
  throw new Error(`File is not exists:${filePath}`);
}
/**
 * delete folder by force
 * @param {String} folderPath 
 */
export function deldir(folderPath) {
  if (!existsFile(folderPath)) {
    return true;
  }
  try {
    if (isFile(folderPath)) {
      fs.unlinkSync(folderPath);
    } else {
      let list = fs.readdirSync(folderPath);
      for (let i = 0; i < list.length;i++){
        let tmpFilePath = path.join(folderPath, list[i]);
        if (isFile(tmpFilePath)) {
          fs.unlinkSync(tmpFilePath);
        } else {
          deldir(tmpFilePath);
        }
      }
      fs.rmdirSync(folderPath);
    }  
    return true;
  } catch (e) {
    return false;  
  }
}

/**
 * get files in dir
 * @param {String} dir 
 * @param {String} prefix default empty ,for recursion
 * @returns 
 */
export function listFiles(dir, prefix = '') {
  dir = path.normalize(dir);
  if (!fs.existsSync(dir)) return [];
  const files = fs.readdirSync(dir);
  let result = [];
  files.forEach(item => {
    const currentDir = path.join(dir, item);
    const stat = fs.statSync(currentDir);
    if (stat.isFile()) {
      result.push(path.join(prefix, item));
    } else if (stat.isDirectory()) {
      const cFiles = listFiles(currentDir, path.join(prefix, item));
      result = result.concat(cFiles);
    }
  });
  return result;
};

export const getMd5 = filePath => {
  let md5 = crypto.createHash('md5');
  return new Promise(r => {
    if (fs.existsSync(filePath)) {
      let rs = fs.createReadStream(filePath);
      rs.on('data', data => {
        md5.update(data);
      });
      rs.on('close', () => {
        let rst = md5.digest('hex').toLowerCase();
        r(rst);
      })
    } else {
      r('');
    }
  })
}
/**
 * get base64 of file
 * @param {String} filepath 
 * @returns 
 */
export const base64 = (filepath) => {
  return new Promise(function (resolve, reject) {
    fs.readFile(filepath, function (err, content) {
      if (err) {
        reject(err);
      } else {
        let str = content.toString('base64');
        resolve(str)
      }
    })
  });
};
